package com.xcf.cloud.usersvc.service.impl;

import com.xcf.cloud.codeapi.client.CodeClient;
import com.xcf.cloud.userapi.dto.AccountDto;
import com.xcf.cloud.userapi.dto.RegisterInfoDto;
import com.xcf.cloud.usersvc.dao.UserAccountRepository;
import com.xcf.cloud.usersvc.entity.UserAccount;
import com.xcf.cloud.usersvc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private CodeClient codeClient;
    @Autowired
    private UserAccountRepository userAccountRepository;

    @Override
    public String register(RegisterInfoDto registerInfo) {
        Integer validCode = codeClient.validCode(registerInfo.getEmail(), registerInfo.getCode());
        if (validCode != 0) {
            return null;
        }
        if (this.checkRegister(registerInfo.getEmail())) {
            return null;
        }
        String token = UUID.randomUUID().toString();
        UserAccount userAccount = new UserAccount();
        userAccount.setEmail(registerInfo.getEmail());
        userAccount.setPassword(registerInfo.getPassword());
        userAccount.setToken(token);
        userAccountRepository.save(userAccount);
        return token;
    }

    @Override
    public String login(AccountDto account) {
        String email = account.getEmail();
        UserAccount userAccount = userAccountRepository.findTopByEmail(email);
        if (null == userAccount || !userAccount.getPassword().equals(account.getPassword())) {
            return null;
        }
        String token = UUID.randomUUID().toString();
        userAccount.setToken(token);
        userAccountRepository.save(userAccount);

        return token;
    }

    @Override
    public boolean checkRegister(String email) {
        UserAccount userAccount = userAccountRepository.findTopByEmail(email);
        return userAccount != null;
    }

    @Override
    public String getUserInfo(String token) {
        UserAccount userAccount = userAccountRepository.findTopByToken(token);
        return null == userAccount ? null : userAccount.getEmail();
    }
}
